package com.cryptape.cita_wallet.fragment;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.cryptape.cita_wallet.CytonApplication;
import com.cryptape.cita_wallet.activity.ChiBiActivity;
import com.cryptape.cita_wallet.activity.MangoAssociationActivity;
import com.cryptape.cita_wallet.activity.MangoNodeActivity;
import com.cryptape.cita_wallet.activity.MyIncomeActivity;
import com.cryptape.cita_wallet.activity.NewActivateActivity;
import com.cryptape.cita_wallet.activity.RealTimeDataActivity;
import com.cryptape.cita_wallet.activity.cloudminer.CloudMinerActivity;
import com.cryptape.cita_wallet.activity.transfer.TransferActivity;
import com.cryptape.cita_wallet.adapter.MyAutoBannerAdapter;
import com.cryptape.cita_wallet.bean.BannerInfo;
import com.cryptape.cita_wallet.bean.CloudMinerBean;
import com.cryptape.cita_wallet.bean.CouldOrderBean;
import com.cryptape.cita_wallet.bean.MyMIDBean;
import com.cryptape.cita_wallet.constant.ConstantUtil;
import com.cryptape.cita_wallet.event.QueryMIDEvent;
import com.cryptape.cita_wallet.event.RefreshMidEvent;
import com.cryptape.cita_wallet.item.Token;
import com.cryptape.cita_wallet.net.callback.CommonCallback;
import com.cryptape.cita_wallet.net.request.HttpRequestMode;
import com.cryptape.cita_wallet.service.http.TokenService;
import com.cryptape.cita_wallet.util.RSAUtils;
import com.cryptape.cita_wallet.util.TimeUtil;
import com.cryptape.cita_wallet.util.db.DBWalletUtil;
import com.google.gson.Gson;
import com.jianyuyouhun.library.AutoBannerView;
import com.mangoworld.android.R;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import rx.Subscriber;

/**
 * Created by dengming on 11/1/20.
 */

public class MyAppFragment extends NBaseFragment {
    public static final String TAG = SettingsFragment.class.getName();
    private AutoBannerView autoBannerView;
    private LinearLayout ll_hashrate;
    private RelativeLayout rl_exchange;
    private RelativeLayout rl_extract;
    private LinearLayout ll_mid;
    private LinearLayout ll_mango_association;
    private LinearLayout ll_mango_node;
    private LinearLayout ll_cloud_mill;
    private TextView tv_mid_id;

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_my_app;
    }

    @Override
    protected void initView() {
        super.initView();
        ll_hashrate = (LinearLayout) findViewById(R.id.ll_hashrate);
        rl_exchange = (RelativeLayout) findViewById(R.id.rl_exchange);
        rl_extract = (RelativeLayout) findViewById(R.id.rl_extract);
        ll_mid = (LinearLayout) findViewById(R.id.ll_mid);
        ll_mango_association = (LinearLayout) findViewById(R.id.ll_mango);
        ll_mango_node = (LinearLayout) findViewById(R.id.ll_mango_node);
        ll_cloud_mill = (LinearLayout) findViewById(R.id.ll_cloud_mill);
        tv_mid_id = (TextView) findViewById(R.id.tv_mid_id);

        autoBannerView = (AutoBannerView) findViewById(R.id.autoBannerView);
        autoBannerView.setWaitMilliSecond(3000);
        autoBannerView.startImageTimerTask();
//        autoBannerView.setDotGravity(AutoBannerView.DotGravity.LEFT);

        MyAutoBannerAdapter autoBannerAdapter = new MyAutoBannerAdapter(getContext());


        //获取到数据之后调用adapter.notifyDataSetChanged,这里由于封装在adapter里的changeItems了，所以没有调用。
        ArrayList list = new ArrayList<>();
        BannerInfo bannerInfo1 = new BannerInfo();
        bannerInfo1.setId(R.drawable.banner_1);
        BannerInfo bannerInfo2 = new BannerInfo();
        bannerInfo2.setId(R.drawable.banner_2);
        BannerInfo bannerInfo3 = new BannerInfo();
        bannerInfo3.setId(R.drawable.banner_3);
        BannerInfo bannerInfo4 = new BannerInfo();
        bannerInfo4.setId(R.drawable.banner_4);
        list.add(bannerInfo1);
        list.add(bannerInfo2);
        list.add(bannerInfo3);
        list.add(bannerInfo4);
        autoBannerAdapter.changeItems(list);
        autoBannerView.setAdapter(autoBannerAdapter);

        tv_mid_id.setText(CytonApplication.getInstance().MIDCode);
//        initMid();
    }

    private void getCloudMiner() {
        String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", address);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.getCouldOrder(getActivity(), content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    try {
                        List<CouldOrderBean> couldOrderBeanList = (List<CouldOrderBean>) data;
                        if (ObjectUtils.isNotEmpty(couldOrderBeanList)) {
                            CouldOrderBean dataBean = couldOrderBeanList.get(0);
                            if (ObjectUtils.equals(dataBean.getQuota(), "0")) {
                                ll_cloud_mill.setVisibility(View.GONE);
                            } else {
                                ll_cloud_mill.setVisibility(View.VISIBLE);
                            }
                        } else {
                            ll_cloud_mill.setVisibility(View.GONE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    ll_cloud_mill.setVisibility(View.GONE);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtils.dTag("isVisibleToUser", " setUserVisibleHint isVisibleToUser = " + isVisibleToUser);
        if (!isVisibleToUser) {
            queryMid();
            getCloudMiner();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        queryMid();
        getCloudMiner();
        LogUtils.dTag("isVisibleToUser", " onResume = ");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            queryMid();
            getCloudMiner();
        }
        LogUtils.dTag("isVisibleToUser", " onHiddenChanged hidden = " + hidden);
    }

    private void queryMid() {
        try {
            String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
            Map params = MapUtils.newHashMap();
            params.put("address", address);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.findMid(getActivity(), content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    MyMIDBean midBean = (MyMIDBean) data;
                    String mid = "";
                    if (midBean != null) {
                        mid = midBean.getLnvitationCode();
                    }
                    CytonApplication.getInstance().MIDCode = mid;
                    tv_mid_id.setText(mid);
//                ll_mid.setVisibility(ObjectUtils.isEmpty(mid) ? View.VISIBLE : View.GONE);
                    ll_hashrate.setVisibility(ObjectUtils.isEmpty(mid) ? View.GONE : View.VISIBLE);
                    if (SettingsFragment.mMyInvitationCode != null)
                        SettingsFragment.mMyInvitationCode.setVisibility(ObjectUtils.isEmpty(mid) ? View.GONE : View.VISIBLE);
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    CytonApplication.getInstance().MIDCode = "";
                    tv_mid_id.setText("");
                    ll_hashrate.setVisibility(View.GONE);
                    if (SettingsFragment.mMyInvitationCode != null)
                        SettingsFragment.mMyInvitationCode.setVisibility(View.GONE);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initAction() {
        super.initAction();
        ll_hashrate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), ChiBiActivity.class));
            }
        });

        rl_exchange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String date = "2020-01-18 20:38:30";
                long timeStamp = TimeUtil.getTime(date);
                if (new Date().getTime() < timeStamp) {
                    Toast.makeText(getContext(), getString(R.string.oepn_time), Toast.LENGTH_SHORT).show();
                    return;
                }

                Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.ETH, ConstantUtil.ETHEREUM_MAIN_ID);
//                Intent intent = new Intent(getContext(), ExchangeActivity.class);
                Intent intent = new Intent(getContext(), RealTimeDataActivity.class);

                intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
                intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.getExchangeContract());
                startActivity(intent);
//                startActivity(new Intent(getContext(), ExchangeActivity.class));
            }
        });

        rl_extract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(getActivity(),getString(R.string.Not_open_yet),Toast.LENGTH_SHORT).show();

                if (TextUtils.isEmpty(CytonApplication.getInstance().MIDCode)) {
//                    checkMid(R.id.rl_extract);
                    Toast.makeText(getContext(), getString(R.string.tip_please_active), Toast.LENGTH_SHORT).show();
                    return;
                }

                Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getMGPName(), ConstantUtil.ETHEREUM_MAIN_ID);
                token.setContractAddress(ConstantUtil.getMGPToken());
                Intent intent = new Intent(getContext(), MyIncomeActivity.class);
//                Intent intent = new Intent(getContext(), StimulateExtractActivity.class);
                intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
                intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.getDEPOSITCONTRACT());
                startActivity(intent);
////                startActivity(new Intent(getContext(), ExchangeActivity.class));
            }
        });

        ll_mid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                String date = "2020-01-18 18:18:18";
//
//                long timeStamp = TimeUtil.getTime(date);
//                if(new Date().getTime() < timeStamp){
//                    Toast.makeText(getContext(),getString(R.string.oepn_time),Toast.LENGTH_SHORT).show();
//                    return;
//                }

                if (!TextUtils.isEmpty(tv_mid_id.getText())) {
                    ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData mClipData = ClipData.newPlainText("mid", tv_mid_id.getText());
                    if (cm != null) {
                        cm.setPrimaryClip(mClipData);
                        Toast.makeText(getContext(), getString(R.string.has_coppied), Toast.LENGTH_SHORT).show();
                    }
                    return;
                }

                Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getDefaultCoin(), ConstantUtil.ETHEREUM_MAIN_ID);
                Intent intent = new Intent(getContext(), NewActivateActivity.class);
                token.setContractAddress(ConstantUtil.getMGPToken());// "0xb2054aDd212F19581aEB195FDa7644471a996134";
                token.decimals = 18;
                intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
                intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.getRegisterContract());
                startActivity(intent);
            }
        });

        ll_mango_association.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), MangoAssociationActivity.class));
            }
        });

        ll_mango_node.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), MangoNodeActivity.class));
            }
        });

        ll_cloud_mill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), CloudMinerActivity.class));
            }
        });
    }

//    private void checkMemberExistsAddress(){
////        showProgressBar();
//        TokenService.checkMemberExistsAddress().subscribe(new Subscriber<Boolean>() {
//            @Override
//            public void onCompleted() {
//                dismissProgressBar();
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                dismissProgressBar();
//            }
//
//            @Override
//            public void onNext(Boolean result) {
//                if(result){
//                    queryMember();
//                }else{
//                    CytonApplication.getInstance().MIDCode = "";
//                    ((TextView)findViewById(R.id.tv_mid_id)).setText("");
//                }
//            }
//        });
//    }

//    private void queryMember(){
////        showProgressBar();
//        TokenService.queryMember().subscribe(new Subscriber<List<Type>>() {
//            @Override
//            public void onCompleted() {
////                dismissProgressBar();
//            }
//
//            @Override
//            public void onError(Throwable e) {
////                dismissProgressBar();
//            }
//
//            @Override
//            public void onNext(List<Type> types) {
//                if(types != null && types.size() > 2){
//                    String midCode = types.get(1).getValue().toString();
//                    CytonApplication.getInstance().MIDCode = midCode;
//                    ((TextView)findViewById(R.id.tv_mid_id)).setText(midCode);
//                }else{
//                    CytonApplication.getInstance().MIDCode = null;
//                    ((TextView)findViewById(R.id.tv_mid_id)).setText("");
//                }
//            }
//        });
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateMIDEvent(QueryMIDEvent event) {
//        checkMemberExistsAddress();
        queryMid();
//        if(!TextUtils.isEmpty(event.pMid)) {
//            String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
//            TokenService.getUSERBACKUP(address, event.pMid);
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateMIDEvent(RefreshMidEvent event) {
        if (!TextUtils.isEmpty(CytonApplication.getInstance().MIDCode)) {
            ((TextView) findViewById(R.id.tv_mid_id)).setText(CytonApplication.getInstance().MIDCode);
        }
    }
}


//兑换合约
//    let roundCrawdsaleContractAddress = EthereumAddress("0x13e36f75Da630079155D96f79D938f77240BE316")!
////关系合约
//        let iMemberRelationContractAddress = EthereumAddress("0x77B21A3B645DCDFdCEDF462bc94A94E176073e9e")!
////注册合约
//        let iMemberRegistrarContractAddress = EthereumAddress("0xCAb1c6e444c3125699cF62acc6A71c89449C9397")!
////erc777代币合约
//        let iMTokenContractAddress = EthereumAddress("0xb2054aDd212F19581aEB195FDa7644471a996134")!
